package com.jxb.three;

import com.jxb.first.ListNode;

/**
 * 反转链表 II
 *  * 给你单链表的头指针 head 和两个整数 left 和 right ，
 *  * 其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点，
 *  * 返回 反转后的链表 。
 *
 *  思路：设置三个指针，pre,start,next
 *      进行遍历，0,right-left
 *      遍历逻辑：
 *          start.next = next.next;
 *          next.next = pre.next;
 *          pre.next = next;
 *
 *          next = start.next
 *
 * @author jiaobo
 * @date Created in 2024/12/28 21:49
 **/
public class ReverseLinkedListII_92 {

    public static void main(String[] args) {
        ListNode head = new ListNode();
        ListNode l1 = new ListNode();
        l1.val = 2;
        ListNode l2 = new ListNode();
        l2.val = 3;
        ListNode l3 = new ListNode();
        l3.val = 4;
        ListNode l4 = new ListNode();
        l4.val = 5;
        l3.next = l4;
        l2.next = l3;
        l1.next= l2;
        head.next = l1;
        head.val = 1;
        reverseBetween(head,2,4);
        System.out.println("--------");
    }

    public static ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode preNode = dummy;
        //初始化preNode节点
        for (int i = 0;i<left - 1;i++) {
            preNode = preNode.next;
        }

        ListNode startNode = preNode.next;
        ListNode nextNode = startNode.next;

        for (int i = 0;i<right-left;i++) {
            startNode.next = nextNode.next;
            nextNode.next = preNode.next;
            preNode.next = nextNode;
            nextNode = startNode.next;
        }
        return dummy.next;
    }

}
